/******************************************/
/******************************************/
/****  JS Document                     ****/
/****  by Andrew Mahon                 ****/
/****  amahon@gmail.com                ****/
/******************************************/
/******************************************/

(function(tc) {

  tc.fn.y5fetcher = function(options){
    var $y5f = this, _o = {}, _oldestTimestamp = null, _newestFrameWIndex = 0
    
    _o = tc.jQ.extend({
      
    },options)
    
    function _initialize(){
      tc.util.log('y5fetcher._initialize')
      _setup_events()
      _fetchFrames(0,2)
      return $y5f
    }
    
    function _setup_events(){
      tc.util.log('y5fetcher._setup_events')
      tc.events.bind('fetchMoreFrames',_fetchMoreFramesHandler)
      tc.events.bind('checkForNew',_checkForNewHandler)
    }
    
    function _fetchFrames(timestamp,n_frames){
      tc.util.log('y5fetcher._fetchFrames['+timestamp+']['+n_frames+']')
      var _url = '/yeah/'
      if(timestamp || timestamp == 0){
        _url = _url + timestamp + '/'
        if(n_frames || n_frames == 0){
          _url = _url + n_frames + '/'
        }
      }
      tc.util.dump(_url)
      var __reqPars = {
        cache:false,
        success:_fetchFramesSuccessHandler,
        error:_fetchFramesErrorHandler,
        type:'GET',
        url:_url,
        dataType:'json'
      }
      tc.jQ.ajax(__reqPars)
    }
    
    function _fetchFramesSuccessHandler(d,ts,xhttp){
      tc.util.log('y5fetcher._fetchFramesSuccessHandler')
      for(var i in d){
        if(d[i].timestamp){
          if(d[i].timestamp < _oldestTimestamp || !_oldestTimestamp){
            _oldestTimestamp = d[i].timestamp
          }
        }
      }
      tc.events.trigger('dataLoad',{data:d})
    }
    
    function _fetchFramesErrorHandler(e,d){
      tc.util.log('y5fetcher._fetchFramesErrorHandler')
      tc.events.trigger('dataLoadError',e)
    }
    
    function _fetchMoreFramesHandler(e,d){
      tc.util.log('y5fetcher._fetchMoreFramesHandler')
      if(d.n_frames){
        _fetchFrames(_oldestTimestamp,d.n_frames)
      }
    }
    
    function _checkForNewHandler(e,d){
      tc.util.log('y5fetcher._checkForNewHandler')
      if(_newestFrameWIndex){
        //GetFramesNewerThan('http://www.yeahyeahyeahyeahyeah.com', _o.cellblockId, _newestFrameWIndex, _cellblockRecievedHandler)
      }
    }
    
    return _initialize()
  }
})(tc);